package com.ziiwee.reduce.describe;

import com.ziiwee.reduce.commons.utils.StringUtil;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Map;
import java.util.Scanner;

@RestController
@RequestMapping("/describe")
public class DescribeEndpoint {

    private final DescribeHolder describeHolder;

    public DescribeEndpoint(DescribeHolder describeHolder) {
        this.describeHolder = describeHolder;
    }

//    @GetMapping
//    public String showPage() {
//        return getResource(null);
//    }
//
//    @GetMapping("/{fileName}")
//    public String getFile(@PathVariable String fileName) {
//        return getResource(fileName);
//    }
//
//    private String getResource(String name) {
//        name = StringUtil.hasLength(name) ? name : "index.html";
//        String url = String.format("META-INF/resources/%s", name);
//        InputStream resourceAsStream = DescribeEndpoint.class.getClassLoader().getResourceAsStream(url);
//        Assert.notNull(resourceAsStream, "找不到模板");
//        Scanner s = new Scanner(resourceAsStream).useDelimiter("\\A");
//        return s.hasNext() ? s.next() : "";
//    }


    @GetMapping("/controllers")
    public Collection<ControllerDescribe> endpoints() {
        return describeHolder.getControllers().values();
    }

    @GetMapping("/types")
    public Map<String, TypeDescribe> types() {
        return describeHolder.getTypes();
    }

    @GetMapping("/types/{typeName}")
    public TypeDescribe types(@PathVariable String typeName) {
        return describeHolder.getType(typeName);
    }

    public static void main(String[] args) throws IOException {
        URL resource = DescribeEndpoint.class.getClassLoader().getResource("META-INF/resources/public/index.html");
        System.out.println(resource);
    }

}
